package student.aistar.boxSeckillTask;

import org.apache.taglibs.standard.lang.jstl.NullLiteral;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import student.aistar.model.entity.BoxSeckill;
import student.aistar.service.IBoxSeckillService;

import java.util.List;
import java.util.Map;

/**
 * @Description:测试小米音箱秒杀
 * @Auther: zhugefeng
 * @Date:2021/10/15 8:31
 **/
@Component
public class TaskBoxSeckill {

    @Autowired
    private IBoxSeckillService boxSeckillService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0/2 * * * * *")
    public void testTask01() {
//        System.out.println("秒杀活动尚未开始~~~");
        List<Map<String, Object>> datas = boxSeckillService.getAllBoxSeckillBefore();
        if (datas != null && datas.size() > 0) {
            ListOperations lop = redisTemplate.opsForList();
            ValueOperations vop = redisTemplate.opsForValue();

            //遍历datas
            for (Map<String, Object> data : datas) {
                long id = (long) data.get("id");
                Integer num = (Integer) data.get("num");

                long size = lop.size("boxkill_" + id);
                if (size == 0) {
                    vop.set("boxstatus_" + id, "0");
                    for (Integer i = 0; i < num; i++) {
                        //
                        lop.leftPush("boxkill_" + id, id);
                    }
                }
            }
        } else {
//            System.out.println("加载失败~~~");
        }
    }

    //秒杀已经开始,但是尚未结束
    @Scheduled(cron = "0/2 * * * * *")
    public void task02() {
        ValueOperations vop = redisTemplate.opsForValue();
        //加载出正在秒杀的商品
        List<Long> ids = boxSeckillService.getBoxById();
        if (ids != null && ids.size() > 0) {
//            System.out.println("秒杀活动已经启动!!!");
            //更新状态
            for (Long id : ids) {
                //更新redis
                vop.set("boxstatus_" + id, "1");
            }
        }
        //更新mysql
        boxSeckillService.updateBoxState();
    }

    //秒杀活动结束
    @Scheduled(cron = "0/2 * * * * *")
    public void task03() {
        //加载出正在被秒杀商品的秒杀id
        List<Long> ids = boxSeckillService.getBoxEndId();
        if (ids != null && ids.size() > 0) {
//            System.out.println("秒杀活动已经结束~~~~~~");
            //更新状态
            for (Long id : ids) {
                //redis删除
                redisTemplate.delete("boxkill_" + id);
                redisTemplate.delete("boxstatus_" + id);
            }
        }
        boxSeckillService.endBoxActive();
    }
}
